
import mapboxgl = require("mapbox-gl");
import * as React from 'react';

interface Props {
  getBaseMap?(map: mapboxgl.Map): void; // 获取mapbox map实例
}

const mapStyle: React.CSSProperties = {
  position: 'absolute',
  top: 10,
  bottom: 0,
  width: '100%',
};
declare global {
  interface Window {
    _map: mapboxgl.Map;
  }

}

export class BaseMap extends React.PureComponent<Props> {

  private map: mapboxgl.Map | null = null;

  componentDidMount() {
    this.initBaseMap();
  }

  componentWillUnmount() {
    if (this.map === null) {
      return;
    }

    this.map.remove();
    this.map = null;
  }

  render() {
    return (
      <div id="map" style={mapStyle} />
    );
  }

  // 初始化地图
  private initBaseMap = () => {
    mapboxgl.accessToken = 'pk.eyJ1IjoiYmFpanMiLCJhIjoiY2pnN2xtcDFrMG11ZTJ3cWpidWp1M3dkbiJ9.1y9te4hb_j-RMKxJwsNaWA';
    const baseMap: mapboxgl.Map = new mapboxgl.Map({
      container: 'map',
      style: 'mapbox://styles/mapbox/streets-v10',
      center: [103, 36],
      zoom: 3
    });
    // baseMap.showTileBoundaries = true; // 地图debug用的
    baseMap.on('load', () => {
      console.log('map init', baseMap);
      window._map = baseMap;
      baseMap.resize();

      if (this.props.getBaseMap) {
        this.props.getBaseMap(baseMap); // 将实例化map传出去
      }

      baseMap.getCanvas().style.cursor = 'default';
    });
  }
}
